﻿using BackupByFTP.FluentFTPHeilpers;
using BackupByFTP.LoggerFile;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using FileInfo = BackupByFTP.FluentFTPHeilpers.FileInfo;

namespace BackupByFTP
{
    public partial class Form1 : Form
    {
        #region App.config配置文件读取
        /// <summary>
        /// ftp地址
        /// </summary>
        private string ftpServerIP = ConfigurationManager.AppSettings["ftpServerIP"];
        /// <summary>
        /// Bak文件ftp地址端口
        /// </summary>
        private string ftpBakServerPort = ConfigurationManager.AppSettings["ftpBakServerPort"];
        /// <summary>
        /// Bak文件地址ftp账号
        /// </summary>
        private string ftpBakUserID = ConfigurationManager.AppSettings["ftpBakUserID"];
        /// <summary>
        ///  Bak文件备份保存路径
        /// </summary>
        private string saveBakFilePath = ConfigurationManager.AppSettings["saveBakFilePath"].ToString().Trim() + DateTime.Now.ToString("yyyy-MM-dd");
        private string OpenBakFileDirPath = ConfigurationManager.AppSettings["saveBakFilePath"].ToString().Trim();
        /// <summary>
        /// 图片文件ftp地址端口
        /// </summary>
        private string ftpPicServerPort = ConfigurationManager.AppSettings["ftpPicServerPort"];
        /// <summary>
        /// 图片文件地址ftp账号
        /// </summary>
        private string ftpPicUserID = ConfigurationManager.AppSettings["ftpPicUserID"];
        /// <summary>
        /// ftp密码
        /// </summary>
        private string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"];
        /// <summary>
        /// 图片备份文件保存路径
        /// </summary>
        private string savePicFilePath = ConfigurationManager.AppSettings["savePicFilePath"].ToString().Trim();
        /// <summary>
        /// Bak是否下载最新 0-下载最新 1-下载选中项 2-下载全部
        /// </summary>
        private string BakIsDownloadNew = ConfigurationManager.AppSettings["BakIsDownloadNew"];
        /// <summary>
        /// 图片是否下载最新 0-下载最新 1-下载选中项 2-下载全部
        /// </summary>
        private string PicIsDownloadNew = ConfigurationManager.AppSettings["PicIsDownloadNew"];
        /// <summary>
        /// Bak备份下载时间 24小时制 0-24之间取值
        /// </summary>
        private string BakBackupTime = ConfigurationManager.AppSettings["BakBackupTime"];
        /// <summary>
        /// 图片备份下载时间分钟 0-60之间取值
        /// </summary>
        private string PicBackupTimeMinute = ConfigurationManager.AppSettings["PicBackupTimeMinute"];
        /// <summary>
        /// 图片备份下载时间小时 24小时制 0-24之间取值
        /// </summary>
        private string PicBackupTimeHour = ConfigurationManager.AppSettings["PicBackupTimeHour"];
        /// <summary>
        /// 刷新时间 单位分钟
        /// </summary>
        private string FlushTime = ConfigurationManager.AppSettings["FlushTime"];
        /// <summary>
        /// 是否开启自动备份 0-是 1-否
        /// </summary>
        private string IsAutoBackup = ConfigurationManager.AppSettings["IsAutoBackup"];
        /// <summary>
        /// 重启时间差 单位分钟
        /// </summary>
        private string TimeDifference = ConfigurationManager.AppSettings["TimeDifference"];
        /// <summary>
        /// 重启程序时间间隔 单位分钟
        /// </summary>
        private string Timespan = ConfigurationManager.AppSettings["Timespan"];
        /// <summary>
        /// 定时重启 0-24取值 凌晨两点重启
        /// </summary>
        private string Sleeper = ConfigurationManager.AppSettings["Sleeper"];
        #endregion

        #region MyRegion
        private FluentHeilper FluentHeilper = new FluentHeilper();
        /// <summary>
        /// 是否开始备份
        /// </summary>
        private bool IsStartPack = false;
        /// <summary>
        /// 刷新定时器
        /// </summary>
        private System.Windows.Forms.Timer RefreshTimer = new System.Windows.Forms.Timer();
        /// <summary>
        /// 重启定时器
        /// </summary>
        private System.Windows.Forms.Timer ResetTimer = new System.Windows.Forms.Timer();
        #endregion

        public Form1()
        {
            InitializeComponent();
            //自动重启
            ResetTimer.Interval = 1000 * int.Parse(Timespan) * 60;
            ResetTimer.Enabled = true;
            ResetTimer.Tick += ResetTimer_Tick;

            //自动备份
            if (IsAutoBackup == "0")
            {
                //每五分钟刷新一次  int.Parse(FlushTime)
                RefreshTimer.Interval = 1000 * int.Parse(FlushTime) * 60;
                RefreshTimer.Enabled = true;
                RefreshTimer.Tick += RefreshTimer_Tick;
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //开机自启
            //SetAutoRun(true);

            DateTime TimeNow = DateTime.Now;
            if (TimeNow.Hour >= int.Parse(BakBackupTime))
            {
                IsStartPack = true;
            }
            Logger.NowDate = TimeNow.ToString("yyyy-MM-dd");
        }

        #region 每天自动备份
        /// <summary>
        /// 每天自动备份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                DateTime TimeNow = DateTime.Now;
                if (TimeNow.Hour >= int.Parse(BakBackupTime))
                {
                    IsStartPack = true;
                }
                if (FluentHeilper.BAKPOWER == 1)
                {
                    Logger.WriteLogFile("当前正在备份数据库文件！");
                }
                else
                {
                    if (FluentHeilper.IsAlreadyBackup == 1)
                    {
                        Logger.WriteLogFile("当日数据库备份已完成！");
                        Bak_panel_Paint(null, null);
                        Logger.WriteLogFile("Bak_panel_Paint=======刷新成功！");
                    }
                    else
                    {
                        if (IsStartPack)
                        {
                            rtb_Bak.Text = "";
                            btn_BakBackup_Click(null, null);
                            DGV_Bak.Rows[0].Selected = false;
                        }
                        else
                        {
                            Bak_panel_Paint(null, null);
                            Logger.WriteLogFile("Bak_panel_Paint=======刷新成功！");
                        }
                    }
                }
                if (FluentHeilper.PICPOWER == 1)
                {
                    Logger.WriteLogFile("当前正在备份图片文件！");
                }
                else
                {
                    if (TimeNow.Hour == int.Parse(PicBackupTimeHour) && TimeNow.Minute >= int.Parse(PicBackupTimeMinute))
                    {
                        rtb_Pic.Text = "";
                        btn_PicBackup_Click(null, null);
                        DGV_Pic.Rows[0].Selected = false;
                    }
                    else
                    {
                        Pic_panel_Paint(null, null);
                        Logger.WriteLogFile("Pic_panel_Paint=======刷新成功！");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("RefreshTimer_Tick====>" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 自动重启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ResetTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (GetTimeDifference())
                {
                    btn_ProgramReset_Click(null, null);
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("ResetTimer_Tick====>" + ex.Message);
                throw;
            }
        }
        #endregion

        #region 文件列表
        /// <summary>
        /// 图片文件列表
        /// </summary>
        public void PicBackup()
        {
            try
            {
                #region 图片列表
                //父目录
                List<FileInfo> PicFileNameList = FluentHeilper.GetPicFileList(ftpServerIP, ftpPicUserID, ftpPassword, int.Parse(ftpPicServerPort));
                Logger.WriteLogFile("【" + ftpServerIP + ":" + ftpPicServerPort + "】" + "==连接成功!");
                DGV_Pic.DataSource = FluentHeilper.DTSource("FileName", "FileSize", PicFileNameList);

                if (PicIsDownloadNew == "0")
                {
                    var PicFileNames = PicFileNameList.FirstOrDefault();
                    lbl_PicfileName.Text = PicFileNames.Name;
                }
                if (PicIsDownloadNew == "1")
                {
                    lbl_PicfileName.Text = "Sel";
                }
                if (PicIsDownloadNew == "2")
                {
                    lbl_PicfileName.Text = "ALL";
                }
                #endregion
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("PicBackup====>" + ex.Message);
                rtb_Pic.Text = ex.Message;
            }
        }
        /// <summary>
        /// 数据库文件列表
        /// </summary>
        private void BakBackup()
        {
            try
            {
                #region BAK列表
                List<FileInfo> BAKFileNameList = FluentHeilper.GetBakFileList(ftpServerIP, ftpBakUserID, ftpPassword, int.Parse(ftpBakServerPort));
                Logger.WriteLogFile("【" + ftpServerIP + ":" + ftpBakServerPort + "】" + "==连接成功!");
                DGV_Bak.DataSource = FluentHeilper.DTSource("FileName", "FileSize", BAKFileNameList);
                //最新
                if (BakIsDownloadNew == "0")
                {
                    var BakFileNames = BAKFileNameList.FirstOrDefault();
                    lbl_BakfileName.Text = BakFileNames.Name;
                }
                //选中项
                if (BakIsDownloadNew == "1")
                {
                    lbl_BakfileName.Text = "Sel";
                }
                //全部
                if (BakIsDownloadNew == "2")
                {
                    lbl_BakfileName.Text = "ALL";
                }
                #endregion
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("BakBackup====>" + ex.Message);
                rtb_Bak.Text = ex.Message;
            }
        }
        #endregion

        #region 添加序号
        private void DGV_Bak_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, this.DGV_Bak.RowHeadersWidth - 4, e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), this.DGV_Bak.RowHeadersDefaultCellStyle.Font, rectangle, this.DGV_Bak.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("DGV_Bak_RowPostPaint====>" + ex.Message);
                rtb_Bak.Text = ex.Message;
            }
        }

        private void DGV_Pic_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, this.DGV_Pic.RowHeadersWidth - 4, e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), this.DGV_Pic.RowHeadersDefaultCellStyle.Font, rectangle, this.DGV_Pic.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("DGV_Pic_RowPostPaint====>" + ex.Message);
                rtb_Pic.Text = ex.Message;
            }
        }
        #endregion

        #region 行双击事件
        /// <summary>
        /// 图片文件备份下载
        /// </summary>
        private void PicCellDoubleClick()
        {
            try
            {
                FluentHeilper.PICPOWER = 1;
                btn_PicBackup.Enabled = false;
                if (lbl_PicfileName.Text.ToUpper() == "ALL")
                {
                    if (IsAutoBackup == "0")
                    {
                        rtb_Pic.Text += DateTime.Now.ToString("yyyy-MM-dd") + "\n=========================================\n";
                        foreach (DataGridViewRow row in this.DGV_Pic.Rows)
                        {
                            string SelectDir = row.Cells["Col_PicFileName"].Value.ToString();
                            if (string.IsNullOrWhiteSpace(SelectDir))
                            {
                                rtb_Pic.Text += "没有选中任何行！\n";
                                Logger.WriteLogFile("没有选中任何行！");
                                return;
                            }
                            else
                            {
                                string result = FluentHeilper.DownloadPicFile(ftpServerIP, ftpPicUserID, ftpPassword, int.Parse(ftpPicServerPort), savePicFilePath, SelectDir);
                                if (result.Substring(0, 2).ToUpper() == "OK")
                                {
                                    rtb_Pic.Text += result + "==>" + SelectDir + "\n";
                                    Logger.WriteLogFile(result + "==>" + SelectDir + "备份成功！");
                                }
                                else if (result.Substring(0, 4).ToUpper() == "FAIL")
                                {
                                    rtb_Pic.Text += result + "==>" + SelectDir + "\n";
                                }
                                rtb_Pic.Text += "=========== 已完成 ===========\n";
                            }
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    DataGridViewSelectedRowCollection dataSelect = null;
                    DataGridViewRow gridViewRow = null;
                    string SelectDir = "";
                    rtb_Pic.Text += DateTime.Now.ToString("yyyy-MM-dd") + "\n=========================================\n";
                    if (IsAutoBackup == "0")
                    {
                        if (PicIsDownloadNew == "1")
                        {
                            SelectDir = DGV_Pic.SelectedRows[0].Cells["Col_PicFileName"].Value.ToString();
                        }
                        else
                        {
                            gridViewRow = DGV_Pic.Rows[0];
                            if (gridViewRow == null)
                            {
                                rtb_Pic.Text += "没有选中任何行！\n";
                                Logger.WriteLogFile("没有选中任何行！");
                                return;
                            }
                            SelectDir = DGV_Pic.Rows[0].Cells["Col_PicFileName"].Value.ToString();
                        }
                    }
                    else if (IsAutoBackup == "1")
                    {
                        dataSelect = this.DGV_Pic.SelectedRows;
                        if (dataSelect.Count <= 0)
                        {
                            rtb_Pic.Text += "没有选中任何行！\n";
                            Logger.WriteLogFile("没有选中任何行！");
                            return;
                        }
                        SelectDir = dataSelect[0].Cells["Col_BakFileName"].Value.ToString();
                    }
                    else
                    {
                        rtb_Pic.Text += "未识别的配置项[IsAutoBackup]！\n";
                        return;
                    }

                    #region MyRegion
                    string result = FluentHeilper.DownloadPicFile(ftpServerIP, ftpPicUserID, ftpPassword, int.Parse(ftpPicServerPort), savePicFilePath, SelectDir);
                    if (result.Substring(0, 2).ToUpper() == "OK")
                    {
                        rtb_Pic.Text += result + "==>" + SelectDir + "\n";
                        Logger.WriteLogFile(result + "==" + dataSelect + "备份成功！");
                    }
                    else if (result.Substring(0, 4).ToUpper() == "FAIL")
                    {
                        rtb_Pic.Text += result + "==>" + dataSelect + "\n";
                    }
                    rtb_Pic.Text += "=========== 已完成 ===========\n";
                    #endregion
                }
                FluentHeilper.PICPOWER = 0;
                Pic_panel.Refresh();
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("PicCellDoubleClick====>" + ex.Message);
                rtb_Pic.Text = ex.Message;
            }
        }

        /// <summary>
        /// BAK文件备份下载
        /// </summary>
        private void BakCellDoubleClick()
        {
            try
            {
                FluentHeilper.BAKPOWER = 1;
                btn_BakBackup.Enabled = false;
                if (lbl_BakfileName.Text.ToUpper() == "ALL")
                {
                    if (IsAutoBackup == "0")
                    {
                        rtb_Bak.Text += DateTime.Now.ToString("yyyy-MM-dd") + "\n=========================================\n";
                        foreach (DataGridViewRow row in this.DGV_Bak.Rows)
                        {
                            string SelectDir = row.Cells["Col_BakFileName"].Value.ToString();
                            string result = FluentHeilper.DownloadBakFile(ftpServerIP, ftpBakUserID, ftpPassword, int.Parse(ftpBakServerPort), saveBakFilePath, SelectDir, SelectDir);
                            if (string.IsNullOrWhiteSpace(result))
                            {
                                Logger.WriteLogFile(SelectDir + "==>文件已存在！");
                                rtb_Bak.Text += SelectDir + "文件已存在！\n";
                            }
                            else if (result.Substring(0, 2).ToUpper() == "OK")
                            {
                                Logger.WriteLogFile(result + "==" + SelectDir + "备份成功！");
                                rtb_Bak.Text += result + "==>" + SelectDir + "\n";
                            }
                            else if (result.Substring(0, 4).ToUpper() == "FAIL")
                            {
                                rtb_Bak.Text += result + "==>" + SelectDir + "\n";
                            }
                        }
                        rtb_Bak.Text += "=========== 已完成 ===========\n";
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    DataGridViewSelectedRowCollection dataSelect = null;
                    DataGridViewRow gridViewRow = null;
                    string SelectDir = "";
                    rtb_Bak.Text += DateTime.Now.ToString("yyyy-MM-dd") + "\n=========================================\n";
                    if (IsAutoBackup == "0")
                    {
                        if (BakIsDownloadNew == "1")
                        {
                            SelectDir = DGV_Bak.SelectedRows[0].Cells["Col_BakFileName"].Value.ToString();
                        }
                        else
                        {
                            gridViewRow = DGV_Bak.Rows[0];
                            if (gridViewRow == null)
                            {
                                rtb_Bak.Text += "没有选中任何行！\n";
                                Logger.WriteLogFile("没有选中任何行！");
                                return;
                            }
                            SelectDir = DGV_Bak.Rows[0].Cells["Col_BakFileName"].Value.ToString();
                        }
                    }
                    else if (IsAutoBackup == "1")
                    {
                        dataSelect = this.DGV_Bak.SelectedRows;
                        if (dataSelect.Count <= 0)
                        {
                            rtb_Bak.Text += "没有选中任何行！\n";
                            Logger.WriteLogFile("没有选中任何行！");
                            return;
                        }
                        SelectDir = dataSelect[0].Cells["Col_BakFileName"].Value.ToString();
                    }
                    else
                    {
                        rtb_Bak.Text += "未识别的配置项[IsAutoBackup]！\n";
                        return;
                    }
                    #region MyRegion
                    string result = FluentHeilper.DownloadBakFile(ftpServerIP, ftpBakUserID, ftpPassword, int.Parse(ftpBakServerPort), saveBakFilePath, SelectDir, SelectDir);
                    if (string.IsNullOrWhiteSpace(result))
                    {
                        Logger.WriteLogFile(SelectDir + "==>文件已存在！");
                        rtb_Bak.Text += SelectDir + "文件已存在！\n";
                    }
                    else if (result.Substring(0, 2).ToUpper() == "OK")
                    {
                        Logger.WriteLogFile(result + "==" + SelectDir + "备份成功！");
                        rtb_Bak.Text += result + "==>" + SelectDir + "\n";
                    }
                    else if (result.Substring(0, 4).ToUpper() == "FAIL")
                    {
                        rtb_Bak.Text += result + "==>" + SelectDir + "\n";
                    }
                    rtb_Bak.Text += "=========== 已完成 ===========\n";
                    #endregion
                }
                FluentHeilper.BAKPOWER = 0;
                FluentHeilper.IsAlreadyBackup = 1;
                Bak_panel.Refresh();
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("BakCellDoubleClick====>" + ex.Message);
                rtb_Bak.Text = ex.Message;
            }
        }
        #endregion

        #region 点击事件
        /// <summary>
        /// 点击按钮备份BAK文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_BakBackup_Click(object sender, EventArgs e)
        {
            try
            {
                if (FluentHeilper.IsAlreadyBackup == 1)
                {
                    return;
                }
                if (FluentHeilper.BAKPOWER == 1)
                {
                    return;
                }
                if (IsStartPack)
                {
                    CheckForIllegalCrossThreadCalls = false;
                    Thread thread = new Thread(BakCellDoubleClick);
                    thread.Start();
                }
                else
                {
                    return;
                }
                btn_BakBackup.Enabled = false;
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("btn_BakBackup_Click====>" + ex.Message);
                rtb_Bak.Text = ex.Message;
            }
        }

        /// <summary>
        /// 点击按钮备份图片文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_PicBackup_Click(object sender, EventArgs e)
        {
            try
            {
                if (FluentHeilper.PICPOWER == 1)
                {
                    return;
                }
                CheckForIllegalCrossThreadCalls = false;
                Thread thread = new Thread(PicCellDoubleClick);
                thread.Start();
                //btn_PicBackup.Enabled = false;
                //DGV_Pic_CellDoubleClick(null, null);
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("btn_PicBackup_Click====>" + ex.Message);
                rtb_Pic.Text = ex.Message;
            }
        }

        /// <summary>
        /// 按钮刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            try
            {
                if (FluentHeilper.PICBTNPOWER == 1)
                {
                    Logger.WriteLogFile("有文件正在备份，稍后刷新！PICBTNPOWER=====" + FluentHeilper.PICBTNPOWER);
                }
                else
                {
                    Logger.WriteLogFile("Pic_panel_Paint=======刷新成功！");
                    rtb_Pic.Text = "";
                    Pic_panel_Paint(null, null);
                }
                if (FluentHeilper.BAKBTNPOWER == 1)
                {
                    Logger.WriteLogFile("有文件正在备份，稍后刷新！BAKBTNPOWER=====" + FluentHeilper.BAKBTNPOWER);
                }
                else
                {
                    Logger.WriteLogFile("Bak_panel_Paint=======刷新成功！");
                    rtb_Bak.Text = "";
                    Bak_panel_Paint(null, null);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("btn_Refresh_Click====>" + ex.Message);
                rtb_Bak.Text = ex.Message;
            }
        }

        /// <summary>
        /// 查看日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ViewLog_Click(object sender, EventArgs e)
        {
            try
            {
                Logger.OpenLogFile();
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("btn_ViewLog_Click====>" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 打开Bak备份目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OpenBakDir_Click(object sender, EventArgs e)
        {
            try
            {
                //判断该路径下文件夹是否存在，不存在的情况下新建文件夹
                if (!Directory.Exists(OpenBakFileDirPath))
                {
                    Directory.CreateDirectory(OpenBakFileDirPath);
                }
                Process.Start(OpenBakFileDirPath);
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("btn_OpenBakDir_Click====>" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 打开Pic备份目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OpenPicDir_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Directory.Exists(savePicFilePath))
                {
                    Directory.CreateDirectory(savePicFilePath);
                }
                Process.Start(savePicFilePath);
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("btn_OpenPicDir_Click====>" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 打开配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OpenConfigFile_Click(object sender, EventArgs e)
        {
            try
            {
                string ConfigFile = Application.StartupPath + @"\BackupByFTP.exe.config";
                //string ConfigFile = Directory.GetCurrentDirectory() + "\\BackupByFTP.exe.config";
                Process.Start("explorer.exe", ConfigFile);
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("btn_OpenConfigFile_Click====>" + ex.Message);
                throw;
            }
        }
        #endregion

        #region 容器控件重绘
        private void Pic_panel_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                if (FluentHeilper.PICBTNPOWER == 1)
                {
                    btn_PicBackup.Enabled = false;
                }
                else
                {
                    PicBackup();
                    lbl_PicfileName.Text = "";
                    btn_PicBackup.Enabled = true;
                }
                DGV_Pic.Rows[0].Selected = true;
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("Pic_panel_Paint====>" + ex.Message);
                rtb_Pic.Text = ex.Message;
            }
        }
        private void Bak_panel_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                if (FluentHeilper.BAKBTNPOWER == 1)
                {
                    btn_BakBackup.Enabled = false;
                }
                else
                {
                    BakBackup();
                    lbl_BakfileName.Text = "";
                    btn_BakBackup.Enabled = true;
                }
                DGV_Bak.Rows[0].Selected = true;
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("Bak_panel_Paint====>" + ex.Message);
                rtb_Bak.Text = ex.Message;
            }
        }
        #endregion

        #region 禁止窗体关闭
        /// <summary>
        /// 禁止窗体关闭
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            try
            {
                const int WM_SYSCOMMAND = 0x0112;
                const int SC_CLOSE = 0xF060;

                if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
                {
                    return;
                }
                base.WndProc(ref m);
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("WndProc====>" + ex.Message);
                throw;
            }

        }
        #endregion

        #region 重启程序
        /// <summary>
        /// 重启程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ProgramReset_Click(object sender, EventArgs e)
        {
            try
            {
                if (FluentHeilper.PICPOWER == 1 || FluentHeilper.BAKPOWER == 1)
                {
                    Logger.WriteLogFile("有文件正在备份中，禁止重启程序!");
                    return;
                }
                else
                {
                    ReadConfigFile();
                    //RefreshTimer_Tick(null, null);
                    Logger.WriteLogFile("重启成功！");
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("btn_ProgramReset_Click====>" + ex.Message);
                MessageBox.Show("btn_ProgramReset_Click==" + ex.Message);
            }
        }

        /// <summary>
        /// 重新读取配置文件
        /// </summary>
        private void ReadConfigFile()
        {
            try
            {
                Process newprocess = new Process();
                string path = Application.StartupPath;
                newprocess.StartInfo.FileName = path + @"\BackupByFTP.exe";
                newprocess.Start();
                Application.Exit();
                Application.ExitThread();
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("ReadConfigFile====>" + ex.Message);
                MessageBox.Show("ReadConfigFile===" + ex.Message);
            }
        }

        /// <summary>
        /// 距离下一天的00：00：00是否大于时间差 防止重启导致某些问题
        /// </summary>
        /// <param name="TDOA">时间差</param>
        /// <returns></returns>
        private bool GetTimeDifference()
        {
            try
            {
                if (DateTime.Now.Hour == int.Parse(Sleeper))
                {
                    return true;
                }
                return false;
                #region MyRegion
                ////获取当前时间
                //DateTime DateTime1 = DateTime.Now;
                ////第二天的00点00分00秒
                //DateTime DateTime2 = DateTime.Now.AddDays(1).Date;
                ////把2个时间转成TimeSpan,方便计算
                //TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                //TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                ////时间比较，得出差值
                //TimeSpan ts = ts1.Subtract(ts2).Duration();
                ////结果
                //int TimeDifference = ts.Days * 24 * 60 + ts.Hours * 60 + ts.Minutes;
                //if (TimeDifference <= TDOA)
                //{
                //    return false;
                //}
                //return true;
                #endregion
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile("GetTimeDifference====>" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 设置应用程序开机自动运行
        /// </summary>
        /// <param name="fileName">应用程序的文件名</param>
        /// <param name="isAutoRun">是否自动运行，为false时，取消自动运行</param>
        /// <exception cref="System.Exception">设置不成功时抛出异常</exception>
        //public static void SetAutoRun(bool isAutoRun)
        //{
        //    RegistryKey reg = null;
        //    try
        //    {
        //        string path = Application.StartupPath;
        //        string fileName = path + @"\BackupByFTP.exe";
        //        string name = path.Substring(fileName.LastIndexOf(@"\\") + 1);
        //        if (!File.Exists(fileName))
        //            throw new Exception("该文件不存在!");
        //        reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
        //        if (reg == null)
        //            reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
        //        if (isAutoRun)
        //            reg.SetValue(name, fileName);
        //        else
        //            reg.DeleteValue(name, false);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //    finally
        //    {
        //        reg?.Close();
        //    }
        //}
        //另外也可以写成服务，不过服务的话一般是在后台执行的，没有程序界面。
        #endregion
    }
}